package com.sc.service.calculate;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FormulaUtils {

    /**
     * 提取变量名并添加 #
     */
    public static String addHashToVariables(String formula, Map<String, Object> variables) {
        // 正则表达式匹配变量名（中文、英文、数字、下划线）
        Pattern pattern = Pattern.compile("[\\u4e00-\\u9fa5a-zA-Z0-9_]+");
        Matcher matcher = pattern.matcher(formula);

        // 替换变量名为 #变量名
        StringBuffer result = new StringBuffer();
        while (matcher.find()) {
            String variable = matcher.group();
            if (variables.containsKey(variable)) {
                matcher.appendReplacement(result, "#" + variable);
            } else {
                matcher.appendReplacement(result, variable);
            }
        }
        matcher.appendTail(result);

        return result.toString();
    }
}
